<template>
  <lb-layout
    class="app-container energyCoal"
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    :paddBottom="5"
    :needfixBtn="false"
  >
    <!-- 查询 or 新增 or 编辑-->
    <el-row>
      <el-col :span="21">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          class="query-form"
        >
          <el-form-item label="实际能耗数年份:" prop="year">
            <el-date-picker
              v-model="queryParams.year"
              type="year"
              :disabled="!showSearch"
              value-format="yyyy"
              placeholder="请选择"
              @change="handleQuery"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <!-- <el-button
              type="primary"
              icon="el-icon-search"
              size="small"
              @click="handleQuery"
              v-show="addFlage && editFlage"
              v-hasPermi="['energy:manage:list']"
            >
              搜索
            </el-button>
            <el-button
              icon="el-icon-refresh"
              size="small"
              @click="handleresetQuery"
              v-show="addFlage && editFlage"
              v-hasPermi="['energy:manage:list']"
            >
              重置
            </el-button> -->
            <el-button
              icon="el-icon-edit"
              size="small"
              type="primary"
              v-show="addFlage && editFlage"
              @click="handleEdit"
              v-hasPermi="['system:solar-terms:edit']"
            >
              编辑
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="3" class="button-area-ex">
        <el-button
          icon="el-icon-check"
          size="small"
          type="primary"
          :disabled="!addFlage"
          v-show="!editFlage"
          @click="handleEdit"
          v-hasPermi="['system:solar-terms:edit']"
        >
          保存
        </el-button>
        <el-button
          type="primary"
          v-show="!addFlage || !editFlage"
          plain
          size="small"
          @click="handleCancel"
        >
          取消
        </el-button>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="12">
        <barometerPie :piedata="barometerPieData"></barometerPie>
      </el-col>
      <el-col :span="12">
        <div class="tip-box">
          <p><span>1</span> 分配百分比总和100，保持2位小数。</p>
          <p>
            <span>2</span> 小暑、大暑、小寒、大寒默认平均数(4.17)
            的3倍，人工调整时上下浮动不超过30%。其它节
            气人工调整时平均数上下浮动不超过50%。其中“小暑、大暑“、“小寒、大寒”上下相邻两个节气为24节气平均数(4.17)。其它12个节气为一年额度剩余4个平分点(4.17/12=1.39)
          </p>
          <p><span>3</span> 任一节气截止日期就是下一节气的起始日期。</p>
        </div>
      </el-col>
    </el-row>

    <!-- 表格标题 -->
    <div class="table-title mt20">
      <Title name="24节气额度分配管理" :line="false">
        <p style="margin: 0; color: #1263e8">
          根据季节气温变化规律，24节气分配年额度（基准值）百分比：
        </p>
        <!-- 表格 -->
        <el-row :gutter="20" class="mt10">
          <el-form
            :model="listform"
            ref="tableForm"
            :rules="listRules"
            size="small"
          >
            <el-col :span="12">
              <el-table
                :data="listform.list"
                :header-cell-style="{ background: 'rgba(18,99,232,0.04)' }"
                style="width: 100%"
                size="medium"
              >
                <!-- show-summary 合计 -->
                <el-table-column
                  type="index"
                  label="序号"
                  width="60"
                  align="center"
                >
                </el-table-column>
                <el-table-column prop="name" label="节气" align="center">
                  <template slot-scope="scope">
                    <div
                      :class="
                        [
                          '立春',
                          '雨水',
                          '立秋',
                          '处暑',
                          '芒种',
                          '夏至',
                          '大雪',
                          '冬至',
                        ].includes(scope.row.name)
                          ? 'cell-span blue'
                          : ['小暑', '大暑', '小寒', '大寒'].includes(
                              scope.row.name
                            )
                          ? 'cell-span green'
                          : 'cell-span'
                      "
                    >
                      {{ scope.row.name }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="allocationRatio"
                  label="年额度分配比（00.00%）"
                  align="center"
                  min-width="200"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'list.' + scope.$index + '.allocationRatio'"
                      :rules="listRules.allocationRatio"
                      v-show="!inputFlage"
                    >
                      <el-input
                        class="cell-center"
                        size="small"
                        v-model="scope.row.allocationRatio"
                        :readonly="inputFlage"
                        @input="
                          (val) => {
                            replaceDigitDeal(
                              val,
                              2,
                              scope.$index,
                              'allocationRatio',
                              'list'
                            );
                          }
                        "
                      ></el-input>
                    </el-form-item>
                    <div
                      v-show="inputFlage"
                      :class="
                        [
                          '立春',
                          '雨水',
                          '立秋',
                          '处暑',
                          '芒种',
                          '夏至',
                          '大雪',
                          '冬至',
                        ].includes(scope.row.name)
                          ? 'cell-span blue'
                          : ['小暑', '大暑', '小寒', '大寒'].includes(
                              scope.row.name
                            )
                          ? 'cell-span green'
                          : 'cell-span'
                      "
                    >
                      {{ scope.row.allocationRatio }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="month"
                  label="月"
                  min-width="200"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-input-number
                      v-show="!inputFlage"
                      v-model="scope.row.month"
                      :min="1"
                      :max="12"
                      size="small"
                    ></el-input-number>
                    <div v-show="inputFlage" class="cell-span">
                      {{ scope.row.month }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="day"
                  label="日"
                  min-width="200"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-input-number
                      v-show="!inputFlage"
                      v-model="scope.row.day"
                      :min="1"
                      :max="31"
                      size="small"
                    ></el-input-number>
                    <div v-show="inputFlage" class="cell-span">
                      {{ scope.row.day }}
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
            <el-col :span="12">
              <el-table
                :data="listform.list2"
                :header-cell-style="{ background: 'rgba(18,99,232,0.04)' }"
                style="width: 100%"
                size="medium"
              >
                <!-- show-summary 合计 -->
                <el-table-column
                  type="index"
                  label="序号"
                  width="60"
                  align="center"
                >
                  <template slot-scope="scope">
                    <div class="cell-span">
                      {{ scope.$index + 13 }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="节气" align="center">
                  <template slot-scope="scope">
                    <div
                      :class="
                        [
                          '立春',
                          '雨水',
                          '立秋',
                          '处暑',
                          '芒种',
                          '夏至',
                          '大雪',
                          '冬至',
                        ].includes(scope.row.name)
                          ? 'cell-span blue'
                          : ['小暑', '大暑', '小寒', '大寒'].includes(
                              scope.row.name
                            )
                          ? 'cell-span green'
                          : 'cell-span'
                      "
                    >
                      {{ scope.row.name }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="allocationRatio"
                  label="年额度分配比（00.00%）"
                  align="center"
                  min-width="200"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'list.' + scope.$index + '.allocationRatio'"
                      :rules="listRules.allocationRatio"
                      v-show="!inputFlage"
                    >
                      <el-input
                        class="cell-center"
                        size="small"
                        v-model="scope.row.allocationRatio"
                        :readonly="inputFlage"
                        @input="
                          (val) => {
                            replaceDigitDeal(
                              val,
                              2,
                              scope.$index,
                              'allocationRatio',
                              'list2'
                            );
                          }
                        "
                      ></el-input>
                    </el-form-item>
                    <div
                      v-show="inputFlage"
                      :class="
                        [
                          '立春',
                          '雨水',
                          '立秋',
                          '处暑',
                          '芒种',
                          '夏至',
                          '大雪',
                          '冬至',
                        ].includes(scope.row.name)
                          ? 'cell-span blue'
                          : ['小暑', '大暑', '小寒', '大寒'].includes(
                              scope.row.name
                            )
                          ? 'cell-span green'
                          : 'cell-span'
                      "
                    >
                      {{ scope.row.allocationRatio }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="month"
                  label="月"
                  min-width="200"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-input-number
                      v-show="!inputFlage"
                      v-model="scope.row.month"
                      :min="1"
                      :max="12"
                      size="small"
                    ></el-input-number>
                    <div v-show="inputFlage" class="cell-span">
                      {{ scope.row.month }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="day"
                  label="日"
                  min-width="200"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-input-number
                      v-show="!inputFlage"
                      v-model="scope.row.day"
                      :min="1"
                      :max="31"
                      size="small"
                    ></el-input-number>
                    <div v-show="inputFlage" class="cell-span">
                      {{ scope.row.day }}
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-form>
        </el-row>
      </Title>
    </div>
  </lb-layout>
</template>

<script>
import {
  listCoalmanage,
  editCoalemanage,
} from "@/api/energyconsumption/solarTerms";
import { barometerData } from "@/api/quota/energy";
import { validMoney } from "@/utils/validate.js";
import { replaceDigit, deepClone, mul, division } from "@/utils/index";
import barometerPie from "@/views/configuration/standard/solarTerms/components/barometerPie.vue";
import exFooter from "@/views/configuration/standard/components/ex-footer.vue";
export default {
  name: "energyCoal",
  components: {
    barometerPie,
    exFooter,
  },
  dicts: ["energy_source_type"],
  data() {
    return {
      barometerPieData: {},
      showSearch: true, // 显示搜索条件
      // 查询参数
      queryParams: {
        year: null,
      },
      versionsArr: [], // 版本号集合
      // 表格数据
      listform: {
        list: [],
        list2: [],
      },
      listRules: {
        allocationRatio: [
          { required: true, message: "年额度分配比不能为空", trigger: "blur" },
          { validator: this.validMoneytest },
        ],
      },
      inputFlage: true, // 输入框钩子
      editFlage: true, // 编辑钩子
      addFlage: true, // 新增版本钩子
    };
  },
  created() {
    this.initializeGet();
  },
  methods: {
    /* 自定义校验 */
    validMoneytest(rule, value, callback) {
      if (!validMoney(value, 2)) {
        callback("系数格式不正确");
      } else {
        if (value > 100) {
          callback("分配比例不能大于100");
        } else {
          callback();
        }
      }
    },

    // 输入框输入只能是5位小数
    replaceDigitDeal(val, digit, index, key, f) {
      this.listform[f][index][key] = replaceDigit(val, digit);
    },
    initializeGet() {
      const that = this;
      that.queryParams.year = new Date().getFullYear() + "";
      that.handleQuery();
    },
    /* 查询版本对应配置列表 */
    getList() {
      let params = {};
      params.year = this.queryParams.year;
      this.$store.commit("app/updateApiCount", "add");
      barometerData(params)
        .then((res) => {
          // 节气额度分配情况
          let solarTermsQuota = res?.data;
          this.barometerPieDatadeal(solarTermsQuota);
        })
        .catch((err) => {
          this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!300066");
        });
      listCoalmanage(params)
        .then((res) => {
          this.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          const data =
            res.rows && res.rows.length > 0
              ? res.rows.map((item) => {
                  item.allocationRatio = mul(item.allocationRatio, 100);
                  return item;
                })
              : [];
          let list = [];
          let list2 = [];
          for (let i = 0; i < 24; i++) {
            if (i < 12) {
              list.push(data[i]);
            } else {
              list2.push(data[i]);
            }
          }
          this.listform.list = list;
          this.listform.list2 = list2;
        })
        .catch((err) => {
          this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!300201");
        });
    },
    barometerPieDatadeal(data) {
      let series = [];
      let legend = [];
      if (Object.keys(data).length > 0) {
        let xl = data.xaxisData;
        let yl = data.seriesData;
        if (xl.length > 0 && yl.length > 0) {
          if (xl.length == yl.length) {
            xl.map((item, index) => {
              let obj = {
                value: (Number(yl[index]) * 100).toFixed(2),
                name: xl[index],
              };
              series.push(obj);
            });
          }
          legend.push(xl.slice(0, 8));
          legend.push(xl.slice(8, 16));
          legend.push(xl.slice(16, 24));
        }
      }
      this.barometerPieData = {
        seriesdata: series,
        legenddata: legend,
      };
    },
    //! 搜索
    handleQuery() {
      if (!this.queryParams.year) {
        this.$message.warning("搜索必须先选择年份");
        return false;
      }
      this.getList();
    },
    //! 重置按钮
    handleresetQuery() {
      this.getList();
      // this.resetQuery();
      // this.initializeGet();
    },
    //? 重置搜索表单
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        year: new Date().getFullYear() + "",
      };
    },

    //? 清空表格
    restTable() {
      this.listform.list = [];
      this.listform.list2 = [];
    },
    //? 条件搜索框和输入框可否输入
    changeFlage(status) {
      this.inputFlage = status;
      this.showSearch = status;
    },
    //* 编辑
    handleEdit() {
      if (this.editFlage) {
        // 编辑时打开编辑权限 按钮变保存
        this.editFlage = !this.editFlage;
        this.changeFlage(false);
      } else {
        this.$refs["tableForm"].validate((throu) => {
          if (throu) {
            if (this.listform.list.length == 0) {
              this.$message.error("节气列表不能为空");
            } else {
              this.$confirm("确认编辑节气吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(() => {
                  this.requestEdit();
                })
                .catch(() => {
                  this.$message({
                    type: "info",
                    message: "已取消",
                  });
                });
            }
          }
        });
      }
    },
    // todo 请求编辑接口
    requestEdit() {
      const arr = [
        ...deepClone(this.listform.list),
        ...deepClone(this.listform.list2),
      ];
      const params = {
        data: arr.map((item) => {
          item.allocationRatio = division(item.allocationRatio, 100);
          return item;
        }),
        year: this.queryParams.year,
      };
      this.$store.commit("app/updateApiCount", "add");
      editCoalemanage(params)
        .then((res) => {
          this.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "编辑成功!",
            });
            this.editFlage = true;
            this.changeFlage(true);
            // 重新请求版本号的集合(根据ID请求编辑后的该版本)
            this.initializeGet();
          }
        })
        .catch((err) => {
          this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!300202");
        });
    },

    //* 取消新增或编辑
    handleCancel() {
      this.restTable();
      this.changeFlage(true);
      // 编辑的时候渲染当前的版本号
      if (!this.editFlage) {
        this.editFlage = true;
        this.initializeGet();
      }
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .lb_layout .section .layout-content {
  padding: 0;
}
::v-deep .query-form {
  height: 31px;
}
.energyCoal {
  ::v-deep .el-card__header {
    border-bottom: none;
  }

  ::v-deep .el-table__cell {
    padding: 2px 0;

    .cell {
      height: 30px;
      line-height: 30px;
    }
  }

  // .type-tag {
  //   transform: translateY(-14px);
  // }
  // .cell-span {
  //   // transform: translateY(40px);
  //   transform: translateY(-14px);
  //   // text-align: center;
  // }
  .cell-center {
    // transform: translateY(10px);
    margin-top: 0px;
  }

  .midcol {
    height: 50px;
    position: relative;

    .el-form-item {
      margin: 9px 0 0 20px;
    }
  }

  .midbutton {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .table-area {
    margin-top: 10px;
    position: relative;

    .addbutton-area {
      position: absolute;
      right: 20px;
      top: 20px;
    }

    .gray-box {
      font-size: 16px;

      p {
        font-size: 14px;
        color: #666666;
        margin: 6px 0;
      }
    }
  }

  .tip-box {
    padding: 10px 20px;
    margin-top: 30px;
    background: rgba(18, 99, 232, 0.04);
    border-radius: 8px;

    p {
      font-size: 14px;
      line-height: 30px;
      color: #666666;
      overflow: hidden; //超出的文本隐藏
      text-overflow: ellipsis; //溢出用省略号显示
      display: -webkit-box;
      -webkit-line-clamp: 4; // 超出多少行
      -webkit-box-orient: vertical;
      overflow: hidden;

      span {
        display: inline-block;
        text-align: center;
        width: 20px;
        height: 20px;
        background: rgba(18, 99, 232, 0.3);
        border-radius: 50%;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #3669d4;
        line-height: 20px;
      }
    }
  }
}

.button-area-ex {
  margin-top: 2px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.blue {
  color: #1263e8;
}

.green {
  color: #00999f;
}
</style>
